<template>
	<view class="container">
		<!-- <leeLoading :animateTxt="animateTxt" :shadowBg="shadowBg" :show="show" :type="type"></leeLoading> -->

		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="header-left" @click="goback" style="background-color: antiquewhite;">
				<sea-link type='navigate' url="/page/demo/index">
					<uni-icons type="left" size="30"></uni-icons>
				</sea-link>
			</view>
			<view class="header-title">
				<text>基础信息</text>
			</view>
			<view class="header-right" style="background-color: lightblue;">
				<sea-link type='back'> 保存 </sea-link>
			</view>
		</view>

		<view class="padding">
			<!-- 存在问题 -->
			<view class="form-item">
				<view class="form-row">
					<text class="form-label required"> 存在问题 </text>
					<textarea v-model="form_data.textarea" class="form-textarea" @input="validateField('textarea')"
						placeholder="请描述检查中发现的问题"></textarea>
				</view>
				<view v-if="validation.textarea" class="error-message">
					<text class="error-text">{{ validation.textarea }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import model from './model';

	export default {
		data() {
			return {
				title: 'this is a test',

				// form-data
				form_data: model(),
				// form-validation
				validation: model()
			}
		},
		onLoad() {
			// 
		},
		methods: {
			/**
			 * 返回上一页
			 */
			goback() {
				uni.navigateBack()
			},

			/**
			 * 保存数据 click 事件
			 */
			submit() {
				console.log('save...');
				const ret = this.validateForm();

				// 表单验证
				if (!ret) {
					uni.showToast({
						title: '请填写完整的必填信息',
						icon: 'none',
						duration: 2000
					})
					return
				}

				// 显示确认保存对话框
				uni.showModal({
					title: '确认',
					content: '是否提交当前表单？',
					confirmText: '保存',
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							this.submitForm();
						}
					}
				})
			},

			/**
			 * 提交表单内容
			 */
			submitForm() {
				console.log('submit...')
			},

			/**
			 * 验证表单所有字段
			 * 
			 * @returns {boolean} 是否验证通过
			 */
			validateForm() {
				// check all field
				Object.keys(this.form_data).forEach(key => this.validateField(key));
				// if contain invalid field?
				return !Object.values(this.validation).some(error => error !== '')
			},

			/**
			 * 验证表单字段
			 * 
			 * @param {Object} fieldName 字段名
			 */
			validateField(fieldName) {
				const form_data = this.form_data;
				const validation = this.validation;

				switch (fieldName) {
					case 'textarea':
						if (!form_data.textarea) {
							validation.textarea = '请填写检查中发现的问题'
						} else if (form_data.textarea.length > 255) {
							validation.textarea = '问题描述过长，长度限制为 255。'
						} else {
							validation.textarea = ''
						}
						break
					case 'checkDate':
						if (!form_data.checkDate) {
							validation.checkDate = '请填写检查日期'
						} else {
							validation.checkDate = ''
						}
						break
				}
			}
		}
	}
</script>